﻿using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;

namespace MedicinskiUslugi {

	public partial class frmLogin : Form {

		public frmLogin() {
			InitializeComponent();
		}

		Utility.ModifyRegistry.ModifyRegistry RegistryData = new Utility.ModifyRegistry.ModifyRegistry();
		string[] Databases;
		public String GlavnaFormConnectionString = "";

		SqlConnection LoginConnection;
		SqlCommand LoginCommand;

		private void frmLogin_Load( object sender, EventArgs e ) {

			Jazik.SelectedIndex = int.Parse( RegistryData.Read( "LastLanguage" ) );
			UserName.Text = RegistryData.Read( "LastUser" );
			Databases = RegistryData.Read( "Database" ).ToString().Split( ';' );
			Database.Items.Clear();
			Database.Items.AddRange( Databases );
			Database.SelectedIndex = int.Parse( RegistryData.Read( "LastDatabase" ) );

			if ( UserName.Text.Length > 1 ) {
				this.Password.Focus();
			} else {
				this.UserName.Focus();
			}

			Password.PasswordChar = '*';
		}

		private void btnExit_Click( object sender, EventArgs e ) {
			this.Close();
		}

		private string textToBase64( string sAscii ) {
			System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
			byte[] bytes = encoding.GetBytes( sAscii );
			return System.Convert.ToBase64String( bytes, 0, bytes.Length );
		}

		private string base64ToText( string sbase64 ) {
			byte[] bytes = System.Convert.FromBase64String( sbase64 );
			System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
			return encoding.GetString( bytes, 0, bytes.Length );
		}

		private void btnOk_Click( object sender, EventArgs e ) {
			string DatabaseUserName = RegistryData.Read( "DatabaseUserName" );

			string DatabasePassword = RegistryData.Read( "DatabasePassword" );

			GlavnaFormConnectionString = @"Persist Security Info=True;Data Source=" + RegistryData.Read( "Server" ) + ";Initial Catalog=" + Database.Text + ";Integrated Security=True; User=" + base64ToText( DatabaseUserName ) + "; Password=" + base64ToText( DatabasePassword );

			var config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None );
			var connectionStringsSection = ( ConnectionStringsSection )config.GetSection( "connectionStrings" );
			connectionStringsSection.ConnectionStrings["MedicinskiUslugi.Properties.Settings.Conn"].ConnectionString = GlavnaFormConnectionString;
			config.Save();
			ConfigurationManager.RefreshSection( "connectionStrings" );
			LoginConnection = new SqlConnection( GlavnaFormConnectionString );
			bool ValidationPass = true;
			foreach ( Control control in GroupLogin.Controls ) {
				if ( control is TxtNumeric.TxtNum ) {
					if ( control.BackColor == Color.Tomato || control.BackColor == Color.Red ) {
						control.Focus();
						ValidationPass = false;
						break;
					}
				}
			}

			if ( UserName.IsTextEmpty() || Password.IsTextEmpty() )
				ValidationPass = false;

			if ( ValidationPass ) {
				LoginCommand = new SqlCommand( "SELECT * FROM tblUsers WHERE UserName=@User AND Password=@Pass", LoginConnection );
				LoginCommand.Parameters.AddWithValue( "@User", UserName.Text );
				LoginCommand.Parameters.AddWithValue( "@Pass", Password.Text );
				LoginConnection.Open();

				SqlDataReader LoginChecker = LoginCommand.ExecuteReader();
				string user = "";
				int User_Id = -1;
				string UserFullName = "";
				int UserLevel = -1;
				int Language = -1;

				if ( LoginChecker.HasRows ) {
					LoginChecker.Read();

					User_Id = int.Parse( LoginChecker["Id"].ToString() );
					user = LoginChecker["Username"].ToString();
					UserFullName = LoginChecker["FullName"].ToString();
					Language = int.Parse( LoginChecker["Language"].ToString() );
					UserLevel = int.Parse( LoginChecker["UserLevel"].ToString() );

					LoginConnection.Close();

					this.Hide();

					frmMain GlavnaForma = new frmMain( GlavnaFormConnectionString, User_Id, UserFullName, UserLevel );

					GlavnaForma.WindowState = FormWindowState.Maximized;
					GlavnaForma.ShowInTaskbar = true;
					GlavnaForma.ShowDialog();

					RegistryData.Write( "LastUser", UserName.Text );
					RegistryData.Write( "LastLanguage", Jazik.SelectedIndex.ToString() );
					RegistryData.Write( "LastDatabase", Database.SelectedIndex.ToString() );
				} else {
					LoginConnection.Close();
					MessageBox.Show( "Погрешни податоци" );
					this.UserName.Focus();
					return;
				}
			}
		}
	}
}